package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"projectes/models/mysql"
	"projectes/models/redis"

	"projectes/projectrpc/internal/svc"
	"projectes/projectrpc/projectrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *projectrpc.UpdateRequest) (*projectrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSms" + in.Mobile + "update")

	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证失败")
	}

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("查询账户失败")
	}

	update := mysql.User{
		Model:    gorm.Model{ID: uint(in.Id)},
		Mobile:   in.Mobile,
		Password: in.Password,
	}

	if user.Password == in.NewPassword {
		return nil, fmt.Errorf("新密码与原密码相同")
	}
	update.Password = in.Password
	err := mysql.DB.Debug().Model(&update).Updates(&update).Error

	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}

	return &projectrpc.UpdateResponse{Id: int64(update.ID)}, nil
}
